from django import forms
from apps.forms import FormMixin
from django.core.cache import cache
from .models import User


# 登录提交表单验证
class LoginForm(forms.Form, FormMixin):
    telephone = forms.CharField(max_length=11)
    password = forms.CharField(max_length=10, min_length=6, error_messages={'max_length': '密码长度最多不能超过20个字符',
                                                                            'min_length': '密码长度最少不能少于6个字符'})
    remember = forms.IntegerField(required=False)


# 注册提交表单验证
class RegisterForm(forms.Form, FormMixin):
    telephone = forms.CharField(max_length=11, min_length=11)
    username = forms.CharField(max_length=20, min_length=4)
    password1 = forms.CharField(max_length=10, min_length=6, error_messages={'max_length': '密码长度最多不能超过20个字符',
                                                                             'min_length': '密码长度最少不能少于6个字符'})
    password2 = forms.CharField(max_length=10, min_length=6, error_messages={'max_length': '密码长度最多不能超过20个字符',
                                                                             'min_length': '密码长度最少不能少于6个字符'})
    img_captcha = forms.CharField(max_length=4, min_length=4)
    sms_captcha = forms.CharField(max_length=4, min_length=4)

    def clean(self):
        cleaned_data = super(RegisterForm, self).clean()

        # 验证手机号码
        telephone = cleaned_data.get('telephone')
        print(telephone)
        exists = User.objects.filter(telephone=telephone).exists()
        if exists:
            forms.ValidationError('该手机号已被注册！')

        # 验证密码
        password1 = cleaned_data.get('password1')
        password2 = cleaned_data.get('password2')
        print(password2)
        if password1 != password2:
            raise forms.ValidationError('两次密码输入不一致！')

        # 验证图形验证码
        img_captcha = cleaned_data.get('img_captcha')
        print(img_captcha)
        cached_img_captcha = cache.get(img_captcha.lower())
        if not cached_img_captcha or cached_img_captcha.lower() != img_captcha.lower():
            raise forms.ValidationError('图形验证码错误！')

        # 验证图形验证码
        sms_captcha = cleaned_data.get('sms_captcha')
        print(sms_captcha)
        cached_sms_captcha = cache.get(telephone)
        if not cached_sms_captcha or cached_sms_captcha.lower() != sms_captcha.lower():
            raise forms.ValidationError('短信验证码错误！')

        return cleaned_data
